package com.feibi.study.Utils;


import com.alibaba.fastjson.JSON;
import com.feibi.study.NetWork.BasicResponseBody;
import com.google.gson.Gson;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;

public class JsonUtil {
    public static BasicResponseBody fromJson(String json, Class clazz) throws Exception {
        Type objectType = type(BasicResponseBody.class, clazz);
        Gson gson = new Gson();
//        return JSON.parseObject(json, objectType);
        return gson.fromJson(json, objectType);
    }

    public static Object str2Obj(String json, Class clazz) throws Exception {
        return JSON.parseObject(json, clazz);
    }


    static ParameterizedType type(final Class raw, final Type... args) {
        return new ParameterizedType() {
            public Type getRawType() {
                return raw;
            }

            public Type[] getActualTypeArguments() {
                return args;
            }

            public Type getOwnerType() {
                return null;
            }
        };
    }


    /**
     * 将json字符串转换为map
     *
     * @param jsonString json字符串
     * @return HashMap
     */
    public static HashMap<String, Object> jsonToMap(String jsonString) {
//        GsonBuilder gb = new GsonBuilder();
//        Gson g = gb.create();
//        try {
//            map = g.fromJson(jsonString, new TypeToken<HashMap<String, Object>>() {
//            }.getType());
//        } catch (Exception e) {
//            map = null;
//        }
        HashMap<String, Object> map = null;
        try {
            map = (HashMap<String, Object>) str2Obj(jsonString, HashMap.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }


}
